package cn.itcast.wushangxiantu.Fragment.guozhan;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import cn.itcast.wushangxiantu.UserData.GuoJiaJunDuiData;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.Activity.GuoZhanActivity;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link JunDuiGuanZhiFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class JunDuiGuanZhiFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Context context;
    private View view;
    private ViewHolder viewHolder;
    private int gj_id;

    public JunDuiGuanZhiFragment(Context context, int gj_id) {
        this.context = context;
        this.gj_id = gj_id;
    }

    public JunDuiGuanZhiFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment JunDuiGuanZhiFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static JunDuiGuanZhiFragment newInstance(String param1, String param2) {
        JunDuiGuanZhiFragment fragment = new JunDuiGuanZhiFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_jun_dui_guan_zhi, container, false);
        viewHolder = new ViewHolder(view);
        return view;
    }


    class ViewHolder implements View.OnClickListener {
        public View rootView;
        public TextView tvGuoJiaDj;
        public Button btnAddGuoJia;
        public TextView tvQiBing;
        public Button btnAddQiBing;
        public Button btnQingKongQiBing;
        public Button btnZhaoMuQiBing;
        public TextView tvHuWeiDui;
        public Button btnAddHuWeiDui;
        public Button btnQingKongHuWeiDui;
        public Button btnZhaoMuHuWeiDui;
        public TextView tvNongMing;
        public Button btnAddNongMing;
        public Button btnQingKongNongMing;
        public Button btnZhaoMuNongMing;
        public TextView tvRenKo;
        private GuoJiaJunDuiData data;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tvGuoJiaDj = (TextView) rootView.findViewById(R.id.tvGuoJiaDj);
            this.btnAddGuoJia = (Button) rootView.findViewById(R.id.btnAddGuoJia);
            this.tvQiBing = (TextView) rootView.findViewById(R.id.tvQiBing);
            this.btnAddQiBing = (Button) rootView.findViewById(R.id.btnAddQiBing);
            this.btnQingKongQiBing = (Button) rootView.findViewById(R.id.btnQingKongQiBing);
            this.btnZhaoMuQiBing = (Button) rootView.findViewById(R.id.btnZhaoMuQiBing);
            this.tvHuWeiDui = (TextView) rootView.findViewById(R.id.tvHuWeiDui);
            this.btnAddHuWeiDui = (Button) rootView.findViewById(R.id.btnAddHuWeiDui);
            this.btnQingKongHuWeiDui = (Button) rootView.findViewById(R.id.btnQingKongHuWeiDui);
            this.btnZhaoMuHuWeiDui = (Button) rootView.findViewById(R.id.btnZhaoMuHuWeiDui);
            this.tvNongMing = (TextView) rootView.findViewById(R.id.tvNongMing);
            this.btnAddNongMing = (Button) rootView.findViewById(R.id.btnAddNongMing);
            this.btnQingKongNongMing = (Button) rootView.findViewById(R.id.btnQingKongNongMing);
            this.btnZhaoMuNongMing = (Button) rootView.findViewById(R.id.btnZhaoMuNongMing);
            this.tvRenKo = (TextView) rootView.findViewById(R.id.tvRenKo);
            btnAddGuoJia.setOnClickListener(this);
            btnAddHuWeiDui.setOnClickListener(this);
            btnAddQiBing.setOnClickListener(this);
            btnAddNongMing.setOnClickListener(this);
            btnZhaoMuHuWeiDui.setOnClickListener(this);
            btnZhaoMuQiBing.setOnClickListener(this);
            btnZhaoMuNongMing.setOnClickListener(this);
            btnQingKongHuWeiDui.setOnClickListener(this);
            btnQingKongNongMing.setOnClickListener(this);
            btnQingKongQiBing.setOnClickListener(this);
            try {
                tvGuoJiaDj.setText("仙盟等级" + GuoZhanActivity.getGuoJiaXinXi().getDj());
            }catch (Exception e){
                ToastUtil.toast(context,"出现了点问题，重新打开吧");
            }
            findJunDui(Login.getUser().getUsernumber(), Login.getUser().getPassword());
        }

        private void findJunDui(String usernumber, String password) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=findJunDui" + "&passWord=" + password + "&userNumber=" + usernumber, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("findJunDui", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("findJunDui", res);
                    Message message = new Message();
                    data = new Gson().fromJson(res, GuoJiaJunDuiData.class);
                    message.what = 2;
                    message.obj = data;
                    handler.sendMessage(message);
                }
            });
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btnAddGuoJia:
                    GeneralDialog("弟子管理", "确定消耗" + GuoZhanActivity.getGuoJiaXinXi().getDj() * GuoZhanActivity.getGuoJiaXinXi().getDj() * 500 + "国库金币升级国家吗", 0);
                    break;
                case R.id.btnAddHuWeiDui:
                    GeneralDialog("弟子管理", "确定消耗" + (data.getHwdj() * 500) + "金币给护卫弟子升级吗", 2);
                    break;
                case R.id.btnAddNongMing:
                    GeneralDialog("弟子管理", "确定消耗" + (data.getNmdj() * 500) + "金币给历练弟子升级吗", 3);
                    break;
                case R.id.btnAddQiBing:
                    GeneralDialog("弟子管理", "确定消耗" + (data.getQbdj() * 500) + "金币给讨伐弟子升级吗", 1);
                    break;
                case R.id.btnQingKongHuWeiDui:
                    GeneralDialog("弟子管理", "确定清空护卫弟子数量吗", 5);
                    break;
                case R.id.btnQingKongNongMing:
                    GeneralDialog("弟子管理", "确定清空历练弟子量吗", 6);
                    break;
                case R.id.btnQingKongQiBing:
                    GeneralDialog("弟子管理", "确定清空讨伐弟子数量吗", 4);
                    break;
                case R.id.btnZhaoMuHuWeiDui:
                    GeneralDialog("输入招募人数(费用："+(data.getHwdj()*100)+"魔核/人)", 1);
                    break;
                case R.id.btnZhaoMuNongMing:
                    GeneralDialog("输入招募人数(费用："+(data.getNmdj()*100)+"魔核/人)", 2);
                    break;
                case R.id.btnZhaoMuQiBing:
                    GeneralDialog("输入招募人数(费用："+(data.getQbdj()*100)+"魔核/人)", 0);
                    break;
            }
        }

        public void GeneralDialog(String head, String content, final int num) {
            /**
             * 普通对话框
             * 1标题
             * 2内容
             */
            AlertDialog dialog;
            AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle(head)

                    .setMessage(content)
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            switch (num) {
                                case 0:
                                    addDengji(Login.getUser().getUsernumber(), Login.getUser().getPassword());
                                    break;
                                case 1:
                                    //升级骑兵
                                    addJunDui(Login.getUser().getUsernumber(), Login.getUser().getPassword(), 0);
                                    break;
                                case 2:
                                    addJunDui(Login.getUser().getUsernumber(), Login.getUser().getPassword(), 1);
                                    break;
                                case 3:
                                    addJunDui(Login.getUser().getUsernumber(), Login.getUser().getPassword(), 2);
                                    break;
                                case 4:
                                    deleteJunDui(Login.getUser().getUsernumber(), Login.getUser().getPassword(), 0);
                                    break;
                                case 5:
                                    deleteJunDui(Login.getUser().getUsernumber(), Login.getUser().getPassword(), 1);
                                    break;
                                case 6:
                                    deleteJunDui(Login.getUser().getUsernumber(), Login.getUser().getPassword(), 2);
                                    break;
                            }
                        }
                    });
            dialog = builder.create();
            dialog.show();
        }

        private void addJunDui(String usernumber, String password, int i) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=addJunDui" + "&passWord=" + password + "&userNumber=" + usernumber + "&num=" + i, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("addJunDui", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("addJunDui", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 4;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        private void deleteJunDui(String usernumber, String password, int i) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=deleteJunDui" + "&passWord=" + password + "&userNumber=" + usernumber + "&num=" + i, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("deleteJunDui", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("deleteJunDui", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 3;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        private void GeneralDialog(String hand, final int id) {
            /**
             * 编辑框
             * 1标题
             */
            final AlertDialog dialog;
            final EditText editText = new EditText(context);
            editText.setLines(1);
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
            String content = hand;
            final AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setTitle(content)
                    .setView(editText)
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            int number = Integer.parseInt(editText.getText().toString().trim());
                            if (number <= 0) {
                                ToastUtil.toast(context, "输入正确的数字");
                            } else {
                                JunDuiZhaoMu(Login.getUser().getUsernumber(), Login.getUser().getPassword(), id, number);
                            }
                        }
                    });
            dialog = builder.create();
            dialog.show();
        }

        private void JunDuiZhaoMu(String usernumber, String password, int id, int number) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=JunDuiZhaoMu" + "&passWord=" + password + "&userNumber=" + usernumber + "&num=" + id + "&number=" + number, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("JunDuiZhaoMu", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("JunDuiZhaoMu", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 3;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        private void addDengji(String usernumber, String password) {
            OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=addDengji" + "&passWord=" + password + "&userNumber=" + usernumber, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    try {
                        Log.v("addDengji", e.getMessage());
                    } catch (Exception e1) {

                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String res = response.body().string();
                    Log.v("addDengji", res);
                    Message message = new Message();
                    User user = new Gson().fromJson(res, User.class);
                    message.what = 1;
                    message.obj = user;
                    handler.sendMessage(message);
                }
            });
        }

        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {
                switch (message.what) {
                    case 1:
                        User user = (User) message.obj;
                        if (null != user) {
                            GeneralDialog("操作结果", user.getStw(), -1);
                            EventBus.getDefault().post(new MessageEvent("getGuoJiaXinxi"));
                            tvGuoJiaDj.setText("仙盟等级:" + user.getDj());
                        } else {
                            ToastUtil.toast(context);
                        }
                        break;
                    case 2:
                        GuoJiaJunDuiData data = (GuoJiaJunDuiData) message.obj;
                        if (null != data) {
                            tvHuWeiDui.setText(data.getHwdj() + "级护卫弟子" + data.getHwnumber() + "人");
                            tvNongMing.setText(data.getNmdj() + "级历练弟子" + data.getNmnumber() + "人");
                            tvQiBing.setText(data.getQbdj() + "级讨伐弟子" + data.getQbnumber() + "人");
                            tvRenKo.setText("剩余弟子那就灵石石头魂宠物碎片都不可上架， 游戏内签到分别给第三天3个宠物碎片，第七天给五个宠物碎片，累计签到30次变成宠物碎片*10，有月卡每日签到额外获得2个石魂\n分配:" + (GuoZhanActivity.getGuoJiaXinXi().getDj() * 100 - data.getHwnumber() - data.getNmnumber() - data.getQbnumber()));
                        } else {
                            ToastUtil.toast(context);
                        }
                        break;
                    case 3:
                    case 4:
                        user = (User) message.obj;
                        if (null != user) {
                            GeneralDialog("操作结果", user.getStw(), -1);
                            findJunDui(Login.getUser().getUsernumber(), Login.getUser().getPassword());
                            EventBus.getDefault().post(new MessageEvent("getGuoJiaXinxi"));
                        } else {
                            ToastUtil.toast(context);
                        }
                        break;
                }
                return false;
            }
        });
    }
}